/**
 * Created by master on 2017/7/26.
 */
var GLOBAL_SESSION_KEY = 'HM_MANAGE_TOKEN_V1.0';
var GLOBAL_DATA_AUTH_KEY = 'GLOBAL_DATA_AUTH_KEY_v1.0';
var WEBSITE_INDEX_URI = "index.html";

function setSession(token){
    //sessionStorage.setItem(GLOBAL_SESSION_KEY,token);
    //创建一个cookie并设置有效时间为 7天
    $.cookie(GLOBAL_SESSION_KEY, token, { expires: 7 });
}

function getSession(){
    //return sessionStorage.getItem(GLOBAL_SESSION_KEY);
    return $.cookie(GLOBAL_SESSION_KEY);
}

function checkSession(){
    if(null == getSession()){
        window.parent.location.href = WEBSITE_INDEX_URI;
    }
}

function authorization(){
    if(null == getSession()){
        window.parent.location.href = WEBSITE_INDEX_URI;
    }
    return {
        root: '/',
        headers: {
            Authorization: getSession()
        }
    };
}

window.sessionTimeOut = false;
function errorMsg(response){
    var responseContent = null;
    try{
        responseContent = eval('(' + response.data + ')');
    }catch(e){
        responseContent = response.data;
    }
    try {
        if(responseContent != undefined && !responseContent.metaType.success){
            if('null' == getSession() && !window.sessionTimeOut){
                window.sessionTimeOut = true;
                alert('会话丢失,请重新登陆');
                window.parent.location.href = WEBSITE_INDEX_URI;
                return;
            }
            if('SESSION_TIME_OUT' == responseContent.metaType.code && !window.sessionTimeOut){
                window.sessionTimeOut = true;
                alert(responseContent.metaType.message);
                window.parent.location.href = WEBSITE_INDEX_URI;
                return;
            }

            if(null == responseContent.metaType.code){
                return responseContent.metaType.message;
            }
            return responseContent.metaType.message;
        }
    } catch (e){
        console.error(e);
    }
}

function loadWorkbench(response){
    try{
      var obj = eval('(' + response.data + ')');
      setSession(obj.data.token);//TODO 需要对token进行校验
    }catch(e){
      var obj = response.data;
      setSession(obj.data.token);//TODO 需要对token进行校验
    }
    window.location.href="/main.html#!workbench.html";
}

function logout(){
    //sessionStorage.removeItem(GLOBAL_SESSION_KEY);
    $.cookie(GLOBAL_SESSION_KEY,null);
    window.location.href = WEBSITE_INDEX_URI;
}

Date.prototype.format = function(fmt) {
    var o = {
        "M+" : this.getMonth()+1,                 //月份
        "d+" : this.getDate(),                    //日
        "h+" : this.getHours(),                   //小时
        "m+" : this.getMinutes(),                 //分
        "s+" : this.getSeconds(),                 //秒
        "q+" : Math.floor((this.getMonth()+3)/3), //季度
        "S"  : this.getMilliseconds()             //毫秒
    };
    if(/(y+)/.test(fmt)) {
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    }
    for(var k in o) {
        if(new RegExp("("+ k +")").test(fmt)){
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
        }
    }
    return fmt;
}

function loadPage(path){
    $.ajax({
        type: 'GET',
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        url: path,
        dataType: "html",
        cache:false,
        success: function(data){
            $('#content').html(data);
        },
        beforeSend:function(){
            $('#content').html('<div class="alert alert-info" role="alert">数据加载中 。。。</div>');
        },
        error:function(){
            $('#content').html('<div class="alert alert-danger" role="alert">404页面没找到</div>');
        }
    });
}

function checkField(target,hiddenObj,val){
    var formData = new FormData();
		formData.append('file_data', val);
		$.ajax({
          url: '/restful/base/v1.0/commmon/upload' ,
          type: 'POST',
          data: formData,
          async: false,
          cache: false,
          contentType: false,
          processData: false,
          beforeSend: function(request) {
              request.setRequestHeader("Authorization", getSession());
          },
          success: function (result) {
             console.log(result.data);
             target.attr('src', result.data);
             hiddenObj.val(result.data);
          },
          error: function (returndata) {
              console.log(returndata);
              alert('文件上传失败');
          }
	   });
}

function getQueryString(variable) {
    var path = (location.hash+'').replace("#!","");
    if(path.length > 0) {
        var vars = path.split("?")[1].split("&");
        for (var i=0;i<vars.length;i++) {
            var pair = vars[i].split("=");
            if(pair[0] == variable){return pair[1];}
        }
    }
    return(false);
}

function responseObj(response){
    try{
      return  eval('(' + response.data + ')');
    }catch(e){
      return response.data;
    }
}

function recordDataAuth(dataAuth){
    $.cookie(GLOBAL_DATA_AUTH_KEY, dataAuth, { expires: 7 });
}

function getDataAuth(){
  return $.cookie(GLOBAL_DATA_AUTH_KEY);
}
